<template>
  <div class="bottom-bar">
    <div class="check-content">
      <check-button
        :is-checked="isSelectAll"
        class="check-button"
        @click.native="checkClick"/>
      <span>全选</span>
    </div>

    <div class="price">
      合计:{{totalPrice}}
    </div>

    <div class="calculate" @click="calcClick">
      去计算({{checkLength}})
    </div>
  </div>
</template>

<script>
  import CheckButton from "components/content/checkButton/CheckButton";

  import { mapGetters } from 'vuex';

  export default {
    name: "CartBottomBar",
    components: {
      CheckButton
    },
    computed: {
      ...mapGetters(['cartList']),
      totalPrice() {
        return '￥' + this.cartList.filter(item => item.checked)
          .reduce((preValue, item) => {
          return preValue + item.price * item.count
        }, 0).toFixed(2)
      },
      checkLength() {
        return this.cartList.filter(item => item.checked).length
      },
      isSelectAll() {
        // 一开始为空的时候 需单独处理
        if (!this.cartList.length) return false;

        // 1.使用filter
        // 因为全部遍历了一遍 所以性能不太好
        // return !(this.cartList.filter(item => !item.checked).length);

        // 2.使用find
        // 此处若找到checked属性为false的对象 就返回该对象 则'！对象'结果为false
        // 若没找到 就返回undefined 则'!undefined‘结果为true
        return !this.cartList.find(item => !item.checked);

        // 3.普通遍历
        // for (let item of this.cartList) {
        //   if (!item.checked) {
        //     return false;
        //   }
        // }
        // return true;
      }
    },
    methods: {
      checkClick() {
        if (this.isSelectAll) { // 全部选中
          this.cartList.forEach(item => item.checked = false);
        } else { // 部分或全部不选中
          this.cartList.forEach(item => item.checked = true);
        }
      },
      calcClick() {
        this.$toast.show('请选择要购买的商品', 2000);
      }
    }
  }
</script>

<style scoped>
  .bottom-bar {
    display: flex;
    position: relative;
    height: 40px;
    background-color: #eee;
    line-height: 40px;
    font-size: 14px;
  }

  .check-content {
    display: flex;
    align-items: center;
    margin-left: 10px;
    width: 60px;
  }

  .check-button {
    width: 22px;
    height: 22px;
    line-height: 22px;
    margin-right: 5px;
  }

  .price {
    flex: 1;
    margin-left: 20px;
  }

  .calculate {
    width: 90px;
    background: red;
    color: #fff;
    text-align: center;
  }
</style>
